<template>
  <div class="comment-section">
    <!-- 文章点赞区域 -->
    <div class="article-like-section">
      <button 
        class="like-btn"
        :class="{ liked: articleLiked }"
        @click="toggleArticleLike"
        :disabled="likeLoading"
      >
        <i class="fas fa-heart"></i>
        <span>{{ articleLikeCount }}</span>
      </button>
    </div>

    <!-- 评论输入区域 -->
    <div class="comment-input-section">
      <div class="section-header">
        <h3>
          <i class="fas fa-comment-dots"></i>
          发表评论
        </h3>
        <div class="comment-stats">
          <span class="comment-count">{{ comments.length }} 条评论</span>
        </div>
      </div>
      
      <div class="comment-form">
        <div class="form-layout">
          <div class="left-section">
            <div class="user-info-section">
              <div class="avatar-preview">
                <img :src="previewAvatar" :alt="newComment.nickname || '随机头像'" class="preview-img">
              </div>
              <div class="nickname-section">
                <div class="nickname-with-reset">
                  <span class="nickname-preview">{{ newComment.nickname || currentNickname }}</span>
                  <button 
                    @click="clearNicknameCookie" 
                    class="reset-nickname-btn"
                    title="重置昵称"
                  >
                    <i class="fas fa-undo"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="right-section">
            <div class="form-group">
              <textarea 
                id="content"
                v-model="newComment.content" 
                placeholder="请输入评论内容..."
                class="comment-textarea"
                rows="4"
                maxlength="500"
                @input="updateCharCount"
              ></textarea>
              <div class="textarea-footer">
                <div class="char-count">{{ charCount }}/500</div>
                <div class="input-hint">支持Markdown格式</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="form-actions">
          <button 
            @click="clearForm" 
            class="clear-btn"
            :disabled="submitting"
          >
            <i class="fas fa-eraser"></i>
            清空
          </button>
          <button 
            @click="submitComment" 
            class="submit-btn"
            :disabled="!newComment.content.trim() || submitting || charCount > 500"
          >
            <i class="fas fa-paper-plane" v-if="!submitting"></i>
            <i class="fas fa-spinner fa-spin" v-else></i>
            {{ submitting ? '提交中...' : '发表评论' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comments-list">
      <div class="list-header">
        <h3>
          <i class="fas fa-comments"></i>
          评论列表
        </h3>
        <div class="list-controls">
          <div class="sort-options">
            <button 
              @click="sortComments('time')" 
              class="sort-btn"
              :class="{ active: sortBy === 'time' }"
            >
              <i class="fas fa-clock"></i>
              时间
            </button>
            <button 
              @click="sortComments('likes')" 
              class="sort-btn"
              :class="{ active: sortBy === 'likes' }"
            >
              <i class="fas fa-heart"></i>
              热度
            </button>
          </div>
          <div class="comment-count-badge">{{ comments.length }}</div>
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>加载评论中...</p>
      </div>
      <div v-else-if="comments.length === 0" class="no-comments">
        <div class="empty-state">
          <i class="fas fa-comment-slash"></i>
          <h4>暂无评论</h4>
          <p>快来抢沙发，发表第一条评论吧！</p>
        </div>
      </div>
      <div v-else class="comments">
        <CommentItem 
          v-for="comment in sortedComments" 
          :key="comment.id"
          :comment="comment"
          :current-nickname="currentNickname"
          @reply="handleReply"
          @like="handleCommentLike"
        />
      </div>
    </div>
  </div>
</template>

<script>
import CommentItem from './CommentItem.vue'
import { commentAPI } from '@/api/comment.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'CommentSection',
  components: {
    CommentItem
  },
  props: {
    articleId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      comments: [],
      loading: false,
      submitting: false,
      likeLoading: false,
      articleLiked: false,
      articleLikeCount: 0,
      currentNickname: '',
      sortBy: 'time', // 'time' or 'likes'
      charCount: 0,
      newComment: {
        articleId: this.articleId,
        parentId: null,
        nickname: '',
        content: '',
        isAnonymous: true
      }
    }
  },
  computed: {
    previewAvatar() {
      if (this.newComment.nickname) {
        // 根据昵称生成头像
        const seed = this.newComment.nickname.charCodeAt(0) % 8 + 1
        return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`
      }
      return 'https://api.dicebear.com/7.x/avataaars/svg?seed=default'
    },
    sortedComments() {
      if (!this.comments.length) return []
      
      const sorted = [...this.comments]
      if (this.sortBy === 'time') {
        return sorted.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      } else if (this.sortBy === 'likes') {
        return sorted.sort((a, b) => b.likeCount - a.likeCount)
      }
      return sorted
    }
  },
  async mounted() {
    await this.loadComments()
    await this.loadArticleLikeStatus()
    this.generateRandomNickname()
  },
  methods: {
    // Cookie操作方法
    setCookie(name, value, days = 365) {
      const expires = new Date()
      expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000))
      document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`
    },

    getCookie(name) {
      const nameEQ = name + '='
      const ca = document.cookie.split(';')
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i]
        while (c.charAt(0) === ' ') c = c.substring(1, c.length)
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length)
      }
      return null
    },

    // 保存昵称到cookie
    saveNicknameToCookie(nickname) {
      if (nickname && nickname.trim()) {
        this.setCookie('comment_nickname', nickname.trim(), 365)
      }
    },

    // 从cookie加载昵称
    loadNicknameFromCookie() {
      const savedNickname = this.getCookie('comment_nickname')
      if (savedNickname) {
        this.currentNickname = savedNickname
        this.newComment.nickname = savedNickname
        return true
      }
      return false
    },

    // 清除昵称cookie
    clearNicknameCookie() {
      this.setCookie('comment_nickname', '', -1) // 设置为过期
      this.newComment.nickname = ''
      this.generateRandomNickname() // 重新生成随机昵称
      ElMessage.success('昵称已重置')
    },

    async loadComments() {
      this.loading = true
      try {
        const response = await commentAPI.getCommentsByArticleId(this.articleId)
        if (response.data.success) {
          this.comments = response.data.data
        }
      } catch (error) {
        console.error('加载评论失败:', error)
        ElMessage.error('加载评论失败')
      } finally {
        this.loading = false
      }
    },

    async loadArticleLikeStatus() {
      try {
        const response = await commentAPI.checkArticleLikeStatus(this.articleId, this.currentNickname)
        if (response.data.success) {
          this.articleLiked = response.data.hasLiked
        }
      } catch (error) {
        console.error('加载文章点赞状态失败:', error)
      }
    },

    generateRandomNickname() {
      // 优先从cookie加载昵称
      if (this.loadNicknameFromCookie()) {
        return
      }
      
      // 如果没有保存的昵称，生成随机昵称
      const nicknames = [
        '匿名用户', '访客', '网友', '路人甲', '吃瓜群众', '程序员', '开发者', 
        '技术达人', '代码爱好者', '学习中的小白', '菜鸟程序员', '资深码农'
      ]
      this.currentNickname = nicknames[Math.floor(Math.random() * nicknames.length)]
      this.newComment.nickname = this.currentNickname
    },

    updateCharCount() {
      this.charCount = this.newComment.content.length
    },

    clearForm() {
      this.newComment.content = ''
      this.newComment.parentId = null
      this.charCount = 0
    },

    sortComments(sortType) {
      this.sortBy = sortType
    },

    async submitComment() {
      if (!this.newComment.content.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }

      this.submitting = true
      try {
        const finalNickname = this.newComment.nickname || this.currentNickname
        const commentData = {
          ...this.newComment,
          nickname: finalNickname
        }
        
        const response = await commentAPI.addComment(commentData)
        if (response.data.success) {
          // 保存昵称到cookie
          this.saveNicknameToCookie(finalNickname)
          this.currentNickname = finalNickname
          
          ElMessage.success('评论发表成功')
          this.newComment.content = ''
          await this.loadComments()
        } else {
          ElMessage.error(response.data.message || '评论发表失败')
        }
      } catch (error) {
        console.error('发表评论失败:', error)
        ElMessage.error('评论发表失败')
      } finally {
        this.submitting = false
      }
    },

    async toggleArticleLike() {
      this.likeLoading = true
      try {
        const response = await commentAPI.likeArticle(this.articleId, this.currentNickname)
        if (response.data.success) {
          this.articleLiked = true
          this.articleLikeCount++
          ElMessage.success('点赞成功')
        } else {
          ElMessage.warning(response.data.message || '点赞失败')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        ElMessage.error('点赞失败')
      } finally {
        this.likeLoading = false
      }
    },

    handleReply(parentComment) {
      this.newComment.parentId = parentComment.id
      this.newComment.content = `@${parentComment.nickname} `
      // 滚动到输入框
      const textarea = this.$el.querySelector('.comment-textarea')
      if (textarea) {
        textarea.focus()
        textarea.scrollIntoView({ behavior: 'smooth' })
      }
    },

    async handleCommentLike(commentId) {
      try {
        const response = await commentAPI.likeComment(commentId, this.currentNickname)
        if (response.data.success) {
          ElMessage.success('点赞成功')
          await this.loadComments()
        } else {
          ElMessage.warning(response.data.message || '点赞失败')
        }
      } catch (error) {
        console.error('点赞失败:', error)
        ElMessage.error('点赞失败')
      }
    }
  }
}
</script>

<style scoped>
.comment-section {
  max-width: calc(800px + 380px + 1rem);
  margin: 1.5rem auto 0;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border-radius: 0.8rem;
  border: 1px solid rgba(255, 255, 255, 0.15);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.article-like-section {
  text-align: center;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}

.like-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.6rem 1.2rem;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 1.5rem;
  color: #e0e0e0;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.like-btn:hover:not(:disabled) {
  background: rgba(255, 64, 129, 0.2);
  border-color: #ff4081;
  color: #ff4081;
  transform: translateY(-2px);
}

.like-btn.liked {
  background: rgba(255, 64, 129, 0.3);
  border-color: #ff4081;
  color: #ff4081;
}

.like-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 区域标题样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.8rem;
  padding-bottom: 0.4rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.section-header h3 {
  color: #ffffff;
  font-size: 1rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.4rem;
  margin: 0;
}

.comment-stats {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.comment-count {
  background: rgba(151, 220, 153, 0.2);
  color: #97dc99;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  font-weight: 500;
  border: 1px solid rgba(151, 220, 153, 0.3);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.8rem;
  padding-bottom: 0.4rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.list-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.sort-options {
  display: flex;
  gap: 0.5rem;
}

.sort-btn {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.5rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  color: #a0a0a0;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.sort-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  color: #ffffff;
}

.sort-btn.active {
  background: rgba(151, 220, 153, 0.2);
  border-color: #97dc99;
  color: #97dc99;
}

.comment-count-badge {
  background: var(--gradient-primary);
  color: #ffffff;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.85rem;
  font-weight: 600;
  min-width: 2rem;
  text-align: center;
}

.comment-form {
  margin-bottom: 1rem;
  background: rgba(255, 255, 255, 0.04);
  padding: 0.8rem;
  border-radius: 0.6rem;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.form-layout {
  display: flex;
  gap: 1rem;
  margin-bottom: 0.8rem;
}

.left-section {
  width: 160px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.right-section {
  flex: 1;
}

.user-info-section {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  background: rgba(255, 255, 255, 0.04);
  padding: 0.6rem;
  border-radius: 0.4rem;
  border: 1px solid rgba(255, 255, 255, 0.08);
}

.nickname-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
  align-items: flex-start;
}

.nickname-with-reset {
  display: flex;
  gap: 0.3rem;
  align-items: center;
  width: 100%;
}

.reset-nickname-btn {
  padding: 0.25rem;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 0.25rem;
  color: #d0d0d0;
  font-size: 0.65rem;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  min-width: 1.5rem;
  height: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.reset-nickname-btn:hover {
  background: rgba(255, 107, 107, 0.2);
  border-color: #ff6b6b;
  color: #ff6b6b;
  transform: translateY(-1px);
}

.form-group {
  margin-bottom: 0.8rem;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #ffffff;
  font-weight: 500;
  margin-bottom: 0.5rem;
  font-size: 0.85rem;
}

.nickname-preview {
  color: #ffffff;
  font-weight: 600;
  font-size: 0.85rem;
  display: inline-block;
  line-height: 1.2;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.avatar-group {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-preview {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.1);
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.input-hint {
  font-size: 0.7rem;
  color: #d0d0d0;
  margin-top: 0.2rem;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.textarea-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.5rem;
}

.char-count {
  font-size: 0.7rem;
  color: #d0d0d0;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.char-count.warning {
  color: #ff9800;
}

.char-count.error {
  color: #f44336;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.6rem;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
}

.comment-textarea {
  width: 100%;
  padding: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  color: #ffffff;
  font-size: 0.85rem;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  transition: all 0.3s ease;
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.comment-textarea::placeholder {
  color: #c0c0c0;
  opacity: 1;
  font-size: 0.8rem;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.comment-textarea:focus {
  outline: none;
  border-color: #4fc1ff;
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 0 0 2px rgba(79, 193, 255, 0.3);
}

.submit-btn {
  padding: 0.5rem 1rem;
  background: var(--gradient-primary);
  border: none;
  border-radius: 0.4rem;
  color: #ffffff;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 180, 255, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.clear-btn {
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 0.4rem;
  color: #d0d0d0;
  font-size: 0.8rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.clear-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.12);
  border-color: rgba(255, 255, 255, 0.25);
  color: #ffffff;
  transform: translateY(-1px);
}

.clear-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #e0e0e0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #97dc99;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.no-comments {
  text-align: center;
  padding: 2rem;
  color: #a0a0a0;
  font-style: italic;
}

.comments {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-section {
    max-width: 100%;
    margin: 0.8rem;
    padding: 0.8rem;
  }
  
  .comment-form {
    padding: 0.8rem;
  }
  
  .form-layout {
    flex-direction: column;
    gap: 0.8rem;
  }
  
  .left-section {
    width: 100%;
  }
  
  .user-info-section {
    padding: 0.5rem;
    gap: 0.5rem;
  }
  
  .article-like-section {
    margin-bottom: 0.8rem;
    padding-bottom: 0.8rem;
  }
  
  .like-btn {
    padding: 0.5rem 1rem;
    font-size: 0.85rem;
  }
}
</style>
